// global-timer-manager.js
import { onBeforeUnmount } from 'vue';

export const GlobalTimerManager = {
    timers: [],

    // 添加定时任务
    addTimer(callback, delay, isInterval = false) {
        const id = isInterval
            ? setInterval(callback, delay)
            : setTimeout(callback, delay);

        this.timers.push({ id, isInterval });
        return id;
    },

    // 清除指定的定时任务
    clearTimer(id) {
        this.timers = this.timers.filter(timer => timer.id !== id);
        clearInterval(id);
    },

    // 清除所有定时任务
    clearAllTimers() {
        this.timers.forEach(({ id, isInterval }) => {
            if (isInterval) {
                clearInterval(id);
            } else {
                clearTimeout(id);
            }
        });
        this.timers = [];
    },
};

// 在应用销毁前清理所有定时任务
onBeforeUnmount(() => {
    GlobalTimerManager.clearAllTimers();
});
